import { action, observable } from "mobx";
import app from "../../../apis/app";
import widget from "../../../apis/widget";
import board from "../../../apis/board";
import { toJS } from 'mobx';
import _ from 'lodash';
import Timer from '../../../components/app/analysis/Timer';

export default class AppChartStore {
  @observable widgets = []; // 看板组件
  @observable boardInfo = {};
  @observable noChart = false;
  @observable isInit = false;
  @observable timer = new Timer();

  @action init = (appid, date) => {
    this.isInit = false;
    this.noChart = false;
    app.getBoard(appid).then(data => {
      if (!data) {
        this.isInit = true;
        this.noChart = true;
        return;
      }

      const { dashboardId } = data;

      Promise.all([
        widget.list(dashboardId),
        board.getBoardInfo(dashboardId)
      ]).then(([widgets, boardInfo]) => {
        this.widgets = widgets.map(w => {
          const { params = {} } = w;
          
          if (date && _.isArray(toJS(date))) {
            params.statisticsStartDate = date[0];
            params.statisticsEndDate = date[1];
       
            const dateArr = date[0].split('-');
            if (dateArr.length === 3) {
              params.statisticalmonth = dateArr[0] + '-' + dateArr[1];
              params.statisticalyear = dateArr[0];
            }
          } else if (date) {
            params.statisticsStartDate = date;
            params.statisticsEndDate = date;
            
            const dateArr = date.split('-');
            if (dateArr.length === 3) {
              params.statisticalmonth = dateArr[0] + '-' + dateArr[1];
              params.statisticalyear = dateArr[0];
            }
          }
          w.params = params;
          return w;
        });

        this.timer.setLength(this.getTimerLength(widgets));
        this.boardInfo = boardInfo;
        this.noChart = widgets.length === 0;
        this.isInit = true;
      });
    });

  }

  @action initState = () => {
    this.isInit = false;
    this.widgets = [];
    this.datas = {};
    this.noChart = false;
  }

  getTimerLength = (data) => {
    let i = 0;

    data.forEach((chart) => {
      const config = chart.config;
      
      if (config && config.refresh ) {
        const { enabled } = config.refresh;

        if (enabled) i++;
      }
    });

    return i;
  }
}